// 解析JWT token
export function parseJwt(token) {
  try {
    const base64Url = token.split('.')[1]
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
    const jsonPayload = decodeURIComponent(atob(base64).split('').map(c => {
      return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
    }).join(''))
    return JSON.parse(jsonPayload)
  } catch (error) {
    console.error('解析token失败:', error)
    return null
  }
}

// 获取认证头部
export function getAuthHeader() {
  const token = localStorage.getItem('token')
  return token ? { 'Authorization': `Bearer ${token}` } : {}
}

// 检查是否已登录
export function isLoggedIn() {
  const token = localStorage.getItem('token')
  if (!token) return false
  
  try {
    const decoded = parseJwt(token)
    if (!decoded) return false
    
    // 检查token是否过期
    const currentTime = Date.now() / 1000
    return decoded.exp > currentTime
  } catch (error) {
    console.error('检查登录状态失败:', error)
    return false
  }
}

// 登出
export function logout() {
  localStorage.removeItem('token')
  localStorage.removeItem('isLogged')
  window.location.href = '/login'
} 